<template>
	<view :class="themeName">
		<navbar title="订单详情"></navbar>
		<view class="order-detail" :style="[infoStyle]">
			<!-- Order Status -->
			<view class="order-status text-center">
				<!-- 待支付 -->
				<template v-if="!orderInfo.order_status">
					<view class="order-status-name flex col-center row-center">
						<u-icon name="rmb-circle" size="36" color="rgba(255, 255, 255, 1)" class="m-r-10" />
						<text>{{ orderAction["name"] }}</text>
					</view>
					<view class="order-status-desc m-t-20" v-if="showCountDown">
						<text class="m-r-10">{{$zhTran('支付剩余')}}</text>
						<u-count-down :timestamp="getCountDownSegment(orderInfo.cancel_unpaid_orders_time)"
							:show-days="false" :show-hours="false" :font-size="26" :separator-size="26" color="#FFFFFF"
							separator-color="#FFFFFF" bg-color="unset" separator="zh" @end="showCountDown = false" />
						<text class="m-l-10">{{$zhTran('自动关闭')}}</text>
					</view>
				</template>
				<!-- 订单状态【门店自提】 -->
				<template v-else>
					<view class="order-status-name flex col-center row-center">
						<u-icon name="gift" size="40" color="rgba(255, 255, 255, 1)" class="m-r-10" />
						<text>{{orderAction["name"]}}</text>
					</view>
				</template>
			</view>

			<view class="leader-info p-30 flex">
				<view style="width: 50rpx;" class="flex col-top">
					<u-icon name="map" size="30" color="rgba(105, 193, 103, 1)" />
				</view>
				<view class="info">
					<view class="address">{{leaderInfo.region_address}}</view>
					<view class="name flex">
						<view class="badge m-r-10" :style="{
							backgroundImage: `url(${$getImageUri('resource/image/shopapi/uniapp/leader-badge.png')})`
						}">{{$zhTran('团长')}}</view>
						<text>{{leaderInfo.name}} {{leaderInfo.phone}}</text>
					</view>
				</view>
			</view>
			<view class="leader-address p-30 m-t-20">
				<view class="flex col--center u-border-bottom p-t-20 p-b-20">
					<u-icon name="clock" size="30" color="rgba(105, 193, 103, 1)" />
					<view class="title">{{$zhTran('开始提货时间')}}：<text>{{orderInfo.pickup_time}}</text></view>
				</view>
				<view class="flex col--center u-border-bottom p-t-20 p-b-20">
					<u-icon name="account" size="30" color="rgba(105, 193, 103, 1)" />
					<view class="title">{{$zhTran('提货人')}}：<text>{{orderInfo.user_name}}</text></view>
				</view>
				<view class="flex col--center u-border-bottom p-t-20 p-b-20">
					<u-icon name="phone" size="30" color="rgba(105, 193, 103, 1)" />
					<view class="title">{{$zhTran('手机号')}}：<text>{{orderInfo.user_phone}}</text></view>
				</view>
			</view>

			<!-- 商品 -->
			<view class="contain order-goods">
				<view v-for="(goodsItem, goodsIndex) in goodsList" :key="goodsIndex">
					<goods-card :key="goodsIndex" shape="rectangle" :name="goodsItem.goods_name"
						:image="goodsItem.goods_image" :contain-style="{ height: '280rpx' }" :fieldShowHide="{}"
						:image-style="{ width: '180rpx', height: '180rpx' }" @tap="goGoodsDetail(goodsItem.goods_id)">
						<view class="flex-1" slot="default">
							<u-gap height="80"></u-gap>
							<view class="m-t-10 flex row-between">
								<price :content="goodsItem.goods_price" mainSize="32rpx" minorSize="26rpx"
									:prefix="orderInfo.price_symbol" color="rgba(250, 64, 52, 1)" />
								<text class="lighter sm">x{{ goodsItem.goods_num }}</text>
							</view>
						</view>
					</goods-card>
				</view>
			</view>
			<!-- 账单 -->
			<view class="contain order-bill">
				<view class="cell order-bill__item">
					<view class="cell-label">{{$zhTran('商品金额')}}</view>
					<view class="cell-content">
						<price :content="orderInfo.goods_amount" :prefix="orderInfo.price_symbol"
							color="rgba(250, 64, 52, 1)" />
					</view>
				</view>
				<view class="cell order-bill__item" v-if="orderInfo.discount_amount * 1">
					<view class="cell-label">{{$zhTran('优惠券')}}</view>
					<view class="cell-content">
						<price :content="orderInfo.discount_amount" color="rgba(250, 64, 52, 1)"
							:prefix="'-' + orderInfo.price_symbol" />
					</view>
				</view>
				<view class="cell order-bill__item">
					<view class="cell-content">
						<text class="muted m-r-10">{{$zhTran('实付款')}}:</text>
						<price :content="orderInfo.order_amount" mainSize="32rpx" minorSize="24rpx" :color="themeColor"
							:prefix="orderInfo.price_symbol" color="rgba(250, 64, 52, 1)" />
					</view>
				</view>
			</view>

			<u-gap height="100"></u-gap>
			<!-- Order Operational -->
			<view v-if="orderButtons.length" class="operational">
				<block v-for="buttonItem in orderButtons" :key="buttonItem.event">
					<view :class="['order-button', `order-button--${buttonItem.style}`]"
						@tap="onOrderButtons(buttonItem['event'], orderInfo)">
						{{ buttonItem.name }}
					</view>
				</block>
			</view>

			<u-popup v-model="pickVisible" mode="center" width="90%">
				<!-- <view class="pickup-box" ref="pickupRef">
					<view class="title">{{$zhTran('提货凭证')}}</view>
					<view class="desc flex m-b-20 col-top">
						<view class="info">
							<view class="m-b-20">{{$zhTran('团&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;长')}}：</view>
							<view>{{$zhTran('提货地址')}}：</view>
						</view>
						<view class="text">
							<view class="m-b-20">{{leaderInfo.name}}</view>
							<view>{{leaderInfo.region_address}}</view>
						</view>
					</view>
					<view class="pickup-line"></view>
					<view class="flex row-center">
						<view class="m-t-20 qr-contain " :class="{ 'qr-contain--die': orderInfo.verification_status }">
							<image :src="options.qrcode" mode="widthFix"></image>
						</view>
					</view>
					<view class="m-t-30 qr-code flex row-center">{{$zhTran('提货码')}}：{{ orderInfo.pickup_code }}</view>
				</view> -->
				<ticket-poster ref="poster" :options="options" @success="handleSuccess" @complete="handleComplete" />
				<view class="pickup-btns flex row-between m-t-20">
					<view class="share" @click="saveImageToOther">{{$zhTran('转发好友')}}</view>
					<view class="saveImg" @click="saveImageToAlbum">{{$zhTran('点击保存到相册')}}</view>
				</view>
			</u-popup>

			<!-- 页面状态 -->
			<page-status :status="pageStatus">
				<template #error>
					<u-empty :text="$zhTran('订单异常')"
						:src="$getImageUri('resource/image/shopapi/uniapp/empty/order.png')" :icon-size="280"></u-empty>
				</template>
			</page-status>
		</view>
		<div style="width: 100%;height: 1rpx;overflow: hidden;padding-top: 10rpx;">
			<tki-qrcode ref="qrcode" uni="px" :val="orderInfo.pickup_code" :size="118 * 2" :showLoading="false"
				@result="getQrCodeUrl" />
		</div>
		<loading-view v-show="loading"></loading-view>
	</view>
</template>

<script>
	import {
		apiCommunityGroupPurchaseLeaderDetail,
		apiCommunityGroupPurchaseOrderDetail
	} from "@/api/community_group_purchase";
	import OrderMixin from "@/mixins/community_group_purchase_order";
	import {
		copy
	} from "@/utils/tools";
	import {
		PageStatusEnum,
		PaymentStatusEnum,
		OrderTypeEnum
	} from "@/utils/enum";
	import ticketPoster from "@/bundle2/pages/community_group_purchase/poster/ticket_poster.vue";

	export default {
		name: "CGPOrderDetail",
		mixins: [OrderMixin],
		components: {
			ticketPoster,
		},

		data() {
			return {
				// 页面状态
				pageStatus: PageStatusEnum["LOADING"],
				order_id: "", // 订单ID
				orderInfo: {}, // 订单信息
				goodsList: [], // 商品列表

				orderButtons: [], // 订单按钮组

				showCountDown: true, // 显示倒计时

				// 订单状态
				orderStatus: {
					0: {
						name: this.$zhTran("等待买家付款"),
					},
					1: {
						name: this.$zhTran("待核销"),
					},
					2: {
						name: this.$zhTran("待核销"),
					},
					3: {
						name: this.$zhTran("已完成"),
					},
					4: {
						name: this.$zhTran("订单已关闭"),
					},
				},
				leaderInfo: [],
				pickVisible: false,
				options: {},
				imgPath: '',
				loading: true

			};
		},

		computed: {
			OrderTypeEnum: () => OrderTypeEnum,
			orderAction() {
				return this.orderStatus[this.orderInfo.order_status] || {};
			},
			infoStyle() {
				if ([1, 2].indexOf(this.orderInfo.order_status) > -1) {
					var bgimg = this.$getImageUri('/resource/image/shopapi/default/bg_orange.png')
				} else if (this.orderInfo.order_status == 3) {
					var bgimg = this.$getImageUri('/resource/image/shopapi/default/bg_green.png')
				} else {
					var bgimg = this.$getImageUri('/resource/image/shopapi/default/bg_gray.png')
				}
				return {
					'background-image': `url(${bgimg})`,
				}
			},
		},

		methods: {
			handleCopy: copy,
			// 刷新订单数据
			refreshOrderData() {
				return apiCommunityGroupPurchaseOrderDetail({
						id: this.order_id,
					})
					.then((ndata) => {
						let data = this.$zhTran(ndata)
						this.orderInfo = data;
						this.goodsList = data.order_goods;
						this.orderButtons = this.getOrderStatusButtons(data.btn) ?? [];
						return Promise.resolve(data);
					})
					.catch((err) => {
						return Promise.reject(err);
					});
			},

			getLeaderInfo() {
				return apiCommunityGroupPurchaseLeaderDetail({
					leader_id: this.orderInfo.leader_id
				}).then((data) => {
					this.leaderInfo = this.$zhTran(data)
					return Promise.resolve(data);
				}).catch(err => {
					return Promise.reject(err);
				});
			},


			// 获取倒计时段
			getCountDownSegment(endTimestamp) {
				const startTimestamp = new Date().getTime() / 1000;
				if (endTimestamp - startTimestamp <= 0) this.showCountDown = false;
				return endTimestamp - startTimestamp;
			},

			// 去商品详情
			goGoodsDetail(goods_id) {
				this.$Router.push({
					path: "/bundle2/pages/goods_detail/goods_detail",
					query: {
						id: goods_id,
					},
				});
			},
			// 处理：查看提货码
			handlePickup() {
				this.pickVisible = true
				this.getPoster()
			},
			getPoster() {
				this.$nextTick(function() {
					const refQR = this.$refs["qrcode"];
					refQR._makeCode();
				});
				this.$refs.poster.drawCanvas();
			},
			getQrCodeUrl(val) {
				this.options = {
					name: this.leaderInfo.name,
					region_address: this.leaderInfo.region_address,
					qrcode: val,
					pickup_code: this.orderInfo.pickup_code
				}
				console.log('options', this.options)
			},
			handleSuccess(val) {
				console.log('handleSuccess', this.imgPath)
				this.imgPath = val;
				this.loading = false
			},
			handleComplete() {
				console.log('handleComplete')
				this.loading = false
			},
			saveImageToOther() {
				console.log('imgPath', this.imgPath)
				uni.showShareImageMenu({
					path: this.imgPath
				})
			},
			saveImageToAlbum() {
				// #ifndef H5
				uni.saveImageToPhotosAlbum({
					filePath: this.imgPath,
					success: (res) => {
						this.$toast({
							title: this.$zhTran("保存成功"),
						});
					},
					fail: (err) => {
						this.$toast({
							title: this.$zhTran("保存失败"),
						});
					},
				});
				// #endif
				// #ifdef H5
				this.$toast({
					title: this.$zhTran("请长按图片保存"),
				});
				// #endif
			},
		},

		async onLoad() {
			const options = this.$Route.query;

			try {
				if (!options.order_id) throw new Error(this.$zhTran("订单异常"));
				this.order_id = options.order_id;
				await this.refreshOrderData();
				await this.getLeaderInfo()
				await this.getPoster()
				this.pageStatus = PageStatusEnum["NORMAL"];
			} catch (err) {
				console.log(err);
				// setTimeout(() => {
				// 	this.$Router.back()
				// }, 0.5 * 1000)
				this.pageStatus = PageStatusEnum["ERROR"];
			}

			// 监听全局duringPayment事件
			uni.$on("duringPayment", ({
				result
			}) => {
				if (result === PaymentStatusEnum["SUCCESS"]) {
					this.$Router.back();
					setTimeout(() => {
						this.$toast({
							title: this.$zhTran("支付成功"),
						});
					}, 0.5 * 1000);
					this.refreshOrderData();
				}
			});
		},

		onUnload() {
			uni.$off("duringPayment");
		},
	};
</script>

<style lang="scss" scoped>
	.order-detail {
		background-size: 100% 15%;
		background-repeat: no-repeat;
		padding: 30rpx;
		position: relative;

		.leader-info {
			width: 100%;
			background-color: #fff;
			position: relative;
			border-radius: 10rpx;

			.info {
				width: calc(100% - 100rpx);
				color: rgba(166, 166, 166, 1);
				font-size: 24rpx;

				&>view {
					margin-bottom: 10rpx;
				}

				.address {
					color: rgba(56, 56, 56, 1);
					font-size: 28rpx;
				}

				.name {
					color: rgba(96, 98, 102, 1);
					font-size: 28rpx;

					.badge {
						background-repeat: no-repeat;
						background-size: 100% 100%;
						color: #fff;
						padding: 6rpx 15rpx;
						font-size: 22rpx;
					}
				}
			}
		}

		.leader-address {
			background-color: #fff;
			border-radius: 10rpx;

			.title {
				color: rgba(150, 150, 150, 1);
				font-size: 28rpx;
				margin-left: 20rpx;
			}

			text {
				color: rgba(56, 56, 56, 1);
			}
		}

		.contain {
			margin-top: 20rpx;
			border-radius: 7px;
			background-color: #ffffff;
		}

		// 单元格
		.cell {
			display: flex;
			align-items: center;
			justify-content: space-between;
			font-size: $-font-size-nr;

			&-label {
				width: 142rpx;
			}

			&-content {
				flex: 1;
				display: flex;
				align-items: center;
			}
		}
	}

	.order-status {
		position: relative;
		display: flex;
		flex-direction: column;
		justify-content: center;
		height: 136rpx;
		color: #ffffff;

		&-name {
			font-size: $-font-size-lg;
		}

		&-desc {
			font-size: $-font-size-sm;
		}
	}

	.order-goods {
		&__handle {
			display: flex;
			align-items: center;
			justify-content: flex-end;
			padding: 0 20rpx 20rpx 20rpx;

			&-button {
				padding: 8rpx 30rpx;
				border: $-solid-border;
				border-radius: 60px;
				font-size: $-font-size-sm;
			}
		}
	}

	.order-bill {
		padding: 20rpx;

		&__item {
			height: 60rpx;

			.cell-content {
				justify-content: flex-end;
			}
		}
	}

	.order-info {
		padding: 20rpx;

		&__item {
			height: 60rpx;
		}

		.copy-btn {
			font-size: 24rpx;
			padding: 6rpx 18rpx;
			border-radius: 8rpx;
			@include font_color();
			@include background_color(0.1);
		}
	}

	.qr-code {
		color: rgba(56, 56, 56, 1);
		font-size: 26rpx;
	}

	.operational {
		box-sizing: border-box;
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		height: calc(100rpx + constant(safe-area-inset-bottom));
		height: calc(100rpx + env(safe-area-inset-bottom));
		display: flex;
		align-items: center;
		justify-content: flex-end;
		padding: 0 20rpx constant(safe-area-inset-bottom) 20rpx;
		padding: 0 20rpx env(safe-area-inset-bottom) 20rpx;
		border-top: $-solid-border;
		background-color: #ffffff;

		.order-button {
			box-sizing: border-box;
			padding: 10rpx 30rpx;
			border-radius: 2px;
			font-size: $-font-size-nr;

			&:nth-child(n + 2) {
				margin-left: 20rpx;
			}

			&--primary {
				background-color: rgba(255, 208, 0, 1);
				color: rgba(74, 25, 0, 1);
			}

			&--normal {
				border-width: 1px;
				border-style: solid;
				@include border_color();
				@include font_color();
			}

			&--muted {
				border: $-solid-border;
				color: $-color-lighter;
			}
		}
	}

	.button--copy {
		padding: 4rpx 20rpx;
		border: $-solid-border;
		border-radius: 60px;
		font-size: $-font-size-xs;
	}

	.pickup-box {
		padding: 30rpx;
		background-color: rgba(255, 255, 255, 1);
		border-radius: 10rpx;

		.title {
			color: rgba(56, 56, 56, 1);
			font-size: 32rpx;
			font-weight: bold;
			margin-bottom: 20rpx;
		}

		.info {
			color: rgba(150, 150, 150, 1);
			font-size: 26rpx;
			width: 180rpx;
			text-align: justify;
		}

		.text {
			color: rgba(56, 56, 56, 1);
			font-size: 26rpx;
		}

		.pickup-line {
			margin: 30rpx 0;
			width: 100%;
			height: 1rpx;
			border: 1rpx dashed rgba(226, 226, 226, 1);
		}

		.qr-contain {
			box-sizing: border-box;
			display: flex;
			justify-content: center;
			align-items: center;
			width: 140px;
			height: 140px;
			border: 1px solid #cccccc;
			border-radius: 5px;

			&--die {
				position: relative;

				&::before {
					position: absolute;
					z-index: 99;
					top: 0;
					left: 0;
					right: 0;
					bottom: 0;
					display: block;
					content: "";
					background-color: rgba(255, 255, 255, 0.5);
				}
			}

		}
	}

	.pickup-btns {
		&>view {
			width: calc((100% - 30rpx) / 2);
			font-size: 26rpx;
			color: rgba(34, 34, 34, 1);
			border-radius: 10rpx;
			padding: 20rpx 0;
			background-color: rgba(255, 255, 255, 1);
			text-align: center;
		}

		.saveImg {
			background-color: rgba(255, 208, 0, 1);
		}
	}
</style>